<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'design:negoti:pmNegotiation:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #pmNegotiationMaterialList>
        <a-button
          v-if="record.status == '9' || !record.status ? true : false"
          class="mb-2"
          @click="handlePmNegotiationMaterialAdd2"
          v-auth="'design:negoti:pmNegotiation:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>

        <a-button
          v-if="record.status == '9' || !record.status ? true : false"
          class="mb-2 ml-2"
          @click="handlePmNegotiationMaterialAdd"
          v-auth="'design:negoti:pmNegotiation:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('选择') }}
        </a-button>
        <BasicTable
          @register="registerPmNegotiationMaterialTable"
          @row-click="handlePmNegotiationMaterialRowClick"
        />
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="Flow_PmNegotiation"
        completeText="提交"
        :loading="loadingRef"
        :auth="'design:negoti:pmNegotiation:edit'"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>

    <ListSelect
      ref="qsdlsit"
      v-show="false"
      selectType="materialSelect"
      :checkbox="true"
      :params="queryParams"
      :selectList="listSelectRef"
      @select="handSelect"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsDesignNegotiPmNegotiationForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    PmNegotiation,
    pmNegotiationSave,
    pmNegotiationForm,
  } from '/@/api/design/negoti/pmNegotiation';
  import { BpmButton } from '/@/components/Bpm';
  import { pmProjectinformationTreeData } from '/@/api/proj/info/pmProjectinformation';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('design.negoti.pmNegotiation');
  const { showMessage } = useMessage();
  const record = ref<PmNegotiation>({} as PmNegotiation);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增洽商单') : t('编辑洽商单'),
  }));

  let listSelectRef = ref([]);
  let queryParams = ref({});
  let qsdlsit = ref<any>('');

  const loadingRef = ref(false);

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('申请信息'),
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    // {
    //   label: t('洽商单编号'),
    //   field: 'djno',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 50,
    //   },
    // },
    {
      label: t('工程名称'),
      field: 'projectno',
      fieldLabel: 'projectname',
      component: 'TreeSelect',
      componentProps: {
        api: pmProjectinformationTreeData,
        params: {},
        canSelectParent: false,
        allowClear: false,
        onChange: async (e) => {
          queryParams.value = {
            pcode: e,
          };
          let arr = await pmNegotiationMaterialTable.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            console.log(index);
            // console.log(item,'111');
            await pmNegotiationMaterialTable.deleteTableDataRecord(item);
            // console.log(item,'2222');
          });
        },
      },
      itemProps: { validateTrigger: 'blur' },
      required: true,
    },
    {
      label: t('工程编码'),
      field: 'projectno',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,
      },
      dynamicDisabled: true,
      required: true,
    },
    // {
    //   label: t('涉及水表'),
    //   field: 'isInvolvewatermeter',
    //   component: 'Switch',
    //   componentProps: {
    //     maxlength: 50,
    //   },
    //   required: true,
    // },
    {
      label: t('变更类型'),
      field: 'designchangereasonid',
      component: 'Select',
      componentProps: {
        dictType: 'zf_designChg_reson_type',
        allowClear: true,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('签证图片'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        bizType: 'PmNegotiation_image',
        uploadType: 'image',
      },
      colProps: { lg: 24, md: 24 },
      rules: [
        { required: true },
        {
          validator(_rule, value) {
            return new Promise((resolve, reject) => {
              const len = !value || value['PmNegotiation_image__len'] || 0;
              if (len == 0) reject(t('请上传签证图片！'));
              else resolve();
            });
          },
        },
      ],
      itemProps: { validateTrigger: 'blur' },
    },
    {
      label: t('变更原因'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      required: true,
    },
    // {
    //   label: t('材料增减项'),
    //   field: 'clzjx',
    //   component: 'FormGroup',
    //   colProps: { lg: 24, md: 24 },
    // },
    // {
    //   field: 'pmNegotiationMaterialList',
    //   component: 'Input',
    //   colProps: { lg: 24, md: 24 },
    //   slot: 'pmNegotiationMaterialList',
    // },
    {
      label: t('确认信息'),
      field: 'qrxx',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
      ifShow: computed(() => !record.value.isNewRecord),
    },
    // {
    //   label: t('创建时间'),
    //   field: 'createDate',
    //   component: 'DatePicker',
    //   componentProps: {
    //     format: 'YYYY-MM-DD HH:mm',
    //     showTime: { format: 'HH:mm' },
    //   },
    // },
    {
      label: t('发出时间'),
      field: 'sendDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('发出人编码'),
      field: 'createBy',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },

    {
      label: t('驳回时间'),
      field: 'backResultDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        placeholder: '',
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('驳回人'),
      field: 'backResultPerson',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('驳回原因'),
      field: 'backResult',
      component: 'Input',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('接口错误信息'),
      field: 'errorContent',
      component: 'Input',
      componentProps: {
        maxlength: 500,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    {
      label: t('审核结果'),
      field: 'checkResult',
      component: 'Input',
      componentProps: {
        maxlength: 50,
      },
      dynamicDisabled: true,
      ifShow: computed(() => !record.value.isNewRecord),
    },
    // {
    //   label: t('执行状态'),
    //   field: 'isReject',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'zf_Negotiation_Reject_status',
    //     allowClear: true,
    //   },
    //   rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    // },

    // {
    //   label: t('审核人编码'),
    //   field: 'checkPerson',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 50,
    //   },
    // },
    // {
    //   label: t('审核时间'),
    //   field: 'checkDate',
    //   component: 'DatePicker',
    //   componentProps: {
    //     format: 'YYYY-MM-DD HH:mm',
    //     showTime: { format: 'HH:mm' },
    //   },
    // },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue, updateSchema }] =
    useForm({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 24, md: 24 },
    });

  const [registerPmNegotiationMaterialTable, pmNegotiationMaterialTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handlePmNegotiationMaterialDelete.bind(this, record1),
          },
          auth: 'design:negoti:pmNegotiation:edit',
          ifShow: () => (record.value.status == '9' || !record.value.status ? true : false),
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setPmNegotiationMaterialTableData(_res: Recordable) {
    pmNegotiationMaterialTable.setColumns([
      {
        title: t('调整类型'),
        dataIndex: 'ctype',
        width: 130,
        align: 'center',
        dictType: 'zf_mat_modify_type',
        editRow: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'zf_mat_modify_type',
          allowClear: true,
        },
        editRule: true,
      },
      {
        title: t('材料编码'),
        dataIndex: 'mcode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('材料名称'),
        dataIndex: 'mname',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('规格型号'),
        dataIndex: 'mstd',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('单位'),
        dataIndex: 'munit',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 50,
        },
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 130,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: true,
      },
    ]);
    pmNegotiationMaterialTable.setTableData(record.value.pmNegotiationMaterialList || []);
  }

  function handlePmNegotiationMaterialRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handlePmNegotiationMaterialAdd2() {
    pmNegotiationMaterialTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handlePmNegotiationMaterialAdd() {
    // pmNegotiationMaterialTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
    if (!getFieldsValue().projectno) {
      showMessage('请先选择工程名称！');
      return;
    }
    listSelectRef.value = [];
    qsdlsit.value.handleInputClick();
  }

  function handlePmNegotiationMaterialDelete(record: Recordable) {
    pmNegotiationMaterialTable.deleteTableDataRecord(record);
  }

  async function getPmNegotiationMaterialList() {
    let pmNegotiationMaterialListValid = true;
    let pmNegotiationMaterialList: Recordable[] = [];
    for (const record of pmNegotiationMaterialTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        pmNegotiationMaterialListValid = false;
      }
      pmNegotiationMaterialList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of pmNegotiationMaterialTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      pmNegotiationMaterialList.push({
        ...record,
        status: '1',
      });
    }
    if (!pmNegotiationMaterialListValid) {
      throw { errorFields: [{ name: ['pmNegotiationMaterialList'] }] };
    }
    return pmNegotiationMaterialList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await pmNegotiationForm(data);
    record.value = (res.pmNegotiation || {}) as PmNegotiation;
    record.value.__t = new Date().getTime();
    record.value.isInvolvewatermeter = record.value.isInvolvewatermeter == 'true' ? true : false;
    queryParams.value = {
      pcode: record.value.projectno,
    };
    setFieldsValue(record.value);
    const notEditField = [
      {
        field: 'projectno',
        fieldLabel: 'projectname',
        componentProps: {
          //disabled: record.value.status == '9' || !record.value.status ? false : true,
          disabled: !record.value.isNewRecord,
        },
      },
      {
        field: 'isInvolvewatermeter',
        componentProps: {
          disabled: record.value.status == '9' || !record.value.status ? false : true,
        },
      },
      {
        field: 'designchangereasonid',
        componentProps: {
          disabled: record.value.status == '9' || !record.value.status ? false : true,
        },
      },
      {
        field: 'remarks',
        componentProps: {
          disabled: record.value.status == '9' || !record.value.status ? false : true,
        },
      },
      {
        field: 'dataMap',
        componentProps: {
          disabled: record.value.status == '9' || !record.value.status ? false : true,
        },
      },
    ];
    updateSchema(notEditField);
    // setPmNegotiationMaterialTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handSelect(selectData) {
    let arr = await pmNegotiationMaterialTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.mcode == item.mcode) {
          flag = false;
        }
      });
      if (flag) {
        pmNegotiationMaterialTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          projectno: item.pcode,
          munit: item.unit,
          iqty: item.num,
        });
      }
    });
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      data.bpm = record.value.bpm; // 流程信息
      data.status = record.value.status; // 提交状态
      data.qsType = '2'; 
      loadingRef.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      // data.pmNegotiationMaterialList = await getPmNegotiationMaterialList();
      // console.log('submit', params, data, record);
      const res = await pmNegotiationSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
